import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface CalendarEvent {
  id: string
  title: string
  startDate: Date
  endDate: Date
  allDay: boolean
  color: string
  notes?: string
  location?: string
  calendar: string // 日历分类
}

export const useCalendarStore = defineStore('calendar', () => {
  // 事件列表
  const events = ref<CalendarEvent[]>([
    {
      id: '1',
      title: '团队会议',
      startDate: new Date(2025, 0, 25, 10, 0),
      endDate: new Date(2025, 0, 25, 11, 0),
      allDay: false,
      color: '#007AFF',
      notes: '讨论Q1计划',
      calendar: '工作'
    },
    {
      id: '2',
      title: '项目截止日期',
      startDate: new Date(2025, 0, 28, 18, 0),
      endDate: new Date(2025, 0, 28, 19, 0),
      allDay: false,
      color: '#FF3B30',
      calendar: '工作'
    },
    {
      id: '3',
      title: '健身',
      startDate: new Date(2025, 0, 23, 19, 0),
      endDate: new Date(2025, 0, 23, 20, 30),
      allDay: false,
      color: '#34C759',
      calendar: '个人'
    },
  ])

  // 当前查看的日期
  const currentDate = ref(new Date())
  
  // 视图模式
  const viewMode = ref<'month' | 'week' | 'day'>('month')
  
  // 日历分类
  const calendars = ref([
    { id: 'work', name: '工作', color: '#007AFF', enabled: true },
    { id: 'personal', name: '个人', color: '#34C759', enabled: true },
    { id: 'family', name: '家庭', color: '#FF9500', enabled: true },
    { id: 'holiday', name: '节假日', color: '#FF3B30', enabled: true },
  ])

  // 获取当前月份的所有日期
  const currentMonthDays = computed(() => {
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth()
    
    // 获取当月第一天和最后一天
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    
    // 获取第一天是星期几（0=周日，需要调整为周一开始）
    let firstDayOfWeek = firstDay.getDay()
    firstDayOfWeek = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1
    
    // 计算需要显示的天数（包括上月和下月）
    const days: Date[] = []
    
    // 上个月的日期
    for (let i = firstDayOfWeek - 1; i >= 0; i--) {
      const date = new Date(year, month, -i)
      days.push(date)
    }
    
    // 当月的日期
    for (let i = 1; i <= lastDay.getDate(); i++) {
      days.push(new Date(year, month, i))
    }
    
    // 下个月的日期（补充到6周=42天）
    const remainingDays = 42 - days.length
    for (let i = 1; i <= remainingDays; i++) {
      days.push(new Date(year, month + 1, i))
    }
    
    return days
  })

  // 获取指定日期的事件
  function getEventsForDate(date: Date): CalendarEvent[] {
    return events.value.filter(event => {
      const eventDate = new Date(event.startDate)
      return (
        eventDate.getFullYear() === date.getFullYear() &&
        eventDate.getMonth() === date.getMonth() &&
        eventDate.getDate() === date.getDate()
      )
    })
  }

  // 添加事件
  function addEvent(event: Omit<CalendarEvent, 'id'>) {
    const newEvent: CalendarEvent = {
      ...event,
      id: Date.now().toString(),
    }
    events.value.push(newEvent)
    saveToStorage()
  }

  // 更新事件
  function updateEvent(eventId: string, updates: Partial<CalendarEvent>) {
    const event = events.value.find(e => e.id === eventId)
    if (event) {
      Object.assign(event, updates)
      saveToStorage()
    }
  }

  // 删除事件
  function deleteEvent(eventId: string) {
    events.value = events.value.filter(e => e.id !== eventId)
    saveToStorage()
  }

  // 切换视图
  function setViewMode(mode: 'month' | 'week' | 'day') {
    viewMode.value = mode
  }

  // 导航到今天
  function goToToday() {
    currentDate.value = new Date()
  }

  // 上一月/周/日
  function goToPrevious() {
    const date = new Date(currentDate.value)
    if (viewMode.value === 'month') {
      date.setMonth(date.getMonth() - 1)
    } else if (viewMode.value === 'week') {
      date.setDate(date.getDate() - 7)
    } else {
      date.setDate(date.getDate() - 1)
    }
    currentDate.value = date
  }

  // 下一月/周/日
  function goToNext() {
    const date = new Date(currentDate.value)
    if (viewMode.value === 'month') {
      date.setMonth(date.getMonth() + 1)
    } else if (viewMode.value === 'week') {
      date.setDate(date.getDate() + 7)
    } else {
      date.setDate(date.getDate() + 1)
    }
    currentDate.value = date
  }

  // 格式化日期
  function formatDate(date: Date): string {
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric' 
    })
  }

  // 格式化时间
  function formatTime(date: Date): string {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  // 判断是否是今天
  function isToday(date: Date): boolean {
    const today = new Date()
    return (
      date.getFullYear() === today.getFullYear() &&
      date.getMonth() === today.getMonth() &&
      date.getDate() === today.getDate()
    )
  }

  // 判断是否是当前月
  function isCurrentMonth(date: Date): boolean {
    return (
      date.getFullYear() === currentDate.value.getFullYear() &&
      date.getMonth() === currentDate.value.getMonth()
    )
  }

  // 保存到 localStorage
  function saveToStorage() {
    try {
      const data = {
        events: events.value.map(e => ({
          ...e,
          startDate: e.startDate.toISOString(),
          endDate: e.endDate.toISOString(),
        })),
        calendars: calendars.value,
      }
      localStorage.setItem('vue-desktop:calendar', JSON.stringify(data))
    } catch (_) {
      // 忽略错误
    }
  }

  // 从 localStorage 加载
  function loadFromStorage() {
    try {
      const raw = localStorage.getItem('vue-desktop:calendar')
      if (!raw) return
      
      const data = JSON.parse(raw)
      
      if (data.events) {
        events.value = data.events.map((e: any) => ({
          ...e,
          startDate: new Date(e.startDate),
          endDate: new Date(e.endDate),
        }))
      }
      
      if (data.calendars) {
        calendars.value = data.calendars
      }
    } catch (_) {
      // 忽略错误
    }
  }

  // 清除缓存
  function clearCalendarCache() {
    events.value = []
    currentDate.value = new Date()
    viewMode.value = 'month'
    calendars.value = [
      { id: 'work', name: '工作', color: '#007AFF', enabled: true },
      { id: 'personal', name: '个人', color: '#34C759', enabled: true },
      { id: 'family', name: '家庭', color: '#FF9500', enabled: true },
      { id: 'holiday', name: '节假日', color: '#FF3B30', enabled: true },
    ]
    
    try {
      localStorage.removeItem('vue-desktop:calendar')
    } catch (_) {
      // 忽略错误
    }
  }

  // 初始化加载
  loadFromStorage()

  return {
    events,
    currentDate,
    viewMode,
    calendars,
    currentMonthDays,
    getEventsForDate,
    addEvent,
    updateEvent,
    deleteEvent,
    setViewMode,
    goToToday,
    goToPrevious,
    goToNext,
    formatDate,
    formatTime,
    isToday,
    isCurrentMonth,
    saveToStorage,
    loadFromStorage,
    clearCalendarCache,
  }
})

